import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import {
  PagePostItemtDto,
  PostRegisterDto,
} from '../../dto/post/post-register.dto';
import { Post } from '../../entities/post.entity';
import { Like, Repository } from 'typeorm';

@Injectable()
export class PostService {
  constructor(
    @InjectRepository(Post)
    private readonly postRepository: Repository<Post>,
  ) {}

  async create(createInput: PostRegisterDto | any): Promise<void> {
    const data = this.postRepository.create(createInput);

    await this.postRepository.save(data);
  }

  async remove(id: string): Promise<void> {
    const existing = await this.findOneById(id);
    // 服务器无法根据客户端请求的内容特性完成请求
    if (!existing)
      throw new HttpException(`删除失败，id为${id}的宣传内容不存在`, 406);
    await this.postRepository.remove(existing);
  }

  async update(updateInput: Post): Promise<any> {
    const existing = await this.postRepository.findOne({
      where: {
        id: updateInput.id,
      },
    });
    if (!existing) {
      throw new HttpException(
        `更新失败，id为${updateInput.id}的文章不存在`,
        406,
      );
    }
    Object.assign(existing, updateInput);
    return await this.postRepository.save(existing);
  }

  /**
   * 分页条件
   */
  async page(param: PagePostItemtDto): Promise<[Post[], number]> {
    const { pageSize, pageNo, id, title } = param;
    const where: any = {};
    if (id) where.id = id;
    if (title) where.title = Like(`%${title}%`);

    const [voteList, total] = await this.postRepository.findAndCount({
      where,
      order: {
        createdTime: 'DESC',
      },
      relations: ['poll'],
      take: pageSize,
      skip: (pageNo - 1) * pageSize,
    });

    // 将角色信息筛选为所需字段
    const result = voteList.map((vote) => {
      const { poll, ...voteList } = vote; // 将投票信息和歌手信息分离

      return { ...voteList, poll };
    });

    return [voteList, total];
  }

  /**
   * 根据用户id查询所有的文章
   * @param userId
   * @returns
   */
  async findAll(pollId: string): Promise<Post[]> {
    console.log(pollId, 'userId');
    return await this.postRepository.find({
      where: { poll: { id: pollId } },
    });
  }

  async findOneById(id: string): Promise<Post> {
    return await this.postRepository.findOne({
      where: {
        id,
      },
    });
  }
}
